package com.wutianyi.module.member.impl;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.wutianyi.module.member.MemberDao;
import com.wutianyi.module.member.dataobject.MemberDO;
import com.wutianyi.utils.Utils;

import static com.wutianyi.entity.EntityTypeEnum.Member;
import static com.wutianyi.entity.DataStoreField.DS_P_VALUE;

public class MemberDaoDataStoreImpl implements MemberDao {

	private static DatastoreService datastoreService = DatastoreServiceFactory
			.getDatastoreService();

	@Override
	public MemberDO getMemberByName(String name) {

		Query query = new Query(KeyFactory.createKey(Member.name(), name));
		Entity entity = datastoreService.prepare(query).asSingleEntity();

		if (null != entity) {
			MemberDO member = (MemberDO) Utils.unSerialize(entity
					.getProperty(DS_P_VALUE));
			return member;
		}

		return null;
	}

	@Override
	public void createMember(MemberDO member) {
		setEntity(member);
	}

	private void setEntity(MemberDO member) {
		Entity entity = new Entity(KeyFactory.createKey(Member.name(),
				member.getName()));
		entity.setProperty(DS_P_VALUE, Utils.serialize(member));
		datastoreService.put(entity);
	}

	@Override
	public void updateMember(MemberDO member) {
		setEntity(member);
	}

}
